﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Model.Twitter;
using Twipler.App;
using System.Configuration;
using Twipler.App.Session;
using Twipler.Data.Cache;
using Twipler.Twitter;
using Twipler.Xtensions;
using Twipler.Data.Access;
using Newtonsoft.Json.Linq;
using Twipler.App.DataDoc;
using Newtonsoft.Json;

namespace Twipler.Accounts
{
    public class TwitterUser
    {
    	private int _twitterId;

        private const string FilenameDateFormat = "yyyyMMdd_HHmmss";

        public TwitterUser(int twitterId)
        {
        	_twitterId = twitterId;
        }

        public void BackgroundProcess(IInnerSession innerSession)
        {
        	Thread.Sleep(100);

            TableStore<Follower>.Open(innerSession.Visitor.Id).Copy();
            TableStore<Friend>.Open(innerSession.Visitor.Id).Truncate();
            
            innerSession.ApiCaller.RequestRawAsync(t => t.Users().GetFriends().CreateCursor().AsJson(), GetFriendsNames_Complete, innerSession, true);
			innerSession.ApiCaller.RequestRawAsync(t => t.Users().GetFollowers().CreateCursor().AsJson(), GetFollowersNames_Complete, innerSession, true);
        }

		private void GetFollowersNames_Complete(object s, TwitterResult twitterResult, IInnerSession innerSession)
		{
			if (twitterResult.IsTwitterError)
				return;

			DataDocJson users = new DataDocJson(() => twitterResult.Response);
			if (users.Status != DataDocStatus.Ok)
				return;

			using (TableStore<Follower> followers = TableStore<Follower>.Open(_twitterId))
			using (TableStore<TwitterUserDetails> userStore = TableStore<TwitterUserDetails>.Open())
			{
                foreach (IDataDoc user in users.Select("/users"))
				{
					int twitterId = Convert.ToInt32(user.Find("id").Value);
					string screenname = (string) user.Find("screen_name").Value;
					string profileImg = (string) user.Find("profile_image_url").Value;

                    userStore.Add(twitterId, screenname, profileImg);
					followers.Add(twitterId);
				}
			}

			DataDocValue nextCustor = users.Find("/next_cursor");
			if ((nextCustor != null) && ((long)nextCustor.Value > 0))
				innerSession.ApiCaller.RequestRawAsync(t => t.Users().GetFollowers().GetCursor((long)nextCustor.Value).AsJson(), GetFollowersNames_Complete, innerSession, true);
			else
				UpdateUnfollowedBy();
		}

		
        private void UpdateUnfollowedBy()
        {
			using (TableStore<Follower> followers = TableStore<Follower>.Open(_twitterId))
			using (TableStore<Unfollower> unfollower = TableStore<Unfollower>.Open(_twitterId))
			{
				List<Follower> unfollowed = followers.CopiesDifference();
			
				foreach (Follower jerk in unfollowed)
					unfollower.Add(jerk.Id, DateTime.Now);

				followers.CopyDrop();
			}
        }

        private void GetFriendsNames_Complete(object s, TwitterResult twitterResult, IInnerSession innerSession)
		{
			if (twitterResult.IsTwitterError)
				return;

			DataDocJson users = new DataDocJson(() => twitterResult.Response);
			if (users.Status != DataDocStatus.Ok)
				return;

            using (TableStore<Friend> friends = TableStore<Friend>.Open(_twitterId))
			using (TableStore<TwitterUserDetails> userStore = TableStore<TwitterUserDetails>.Open())
			{
				foreach (IDataDoc user in users.Select("/users"))
				{
					int twitterId = Convert.ToInt32(user.Find("id").Value);
					string screenname = (string) user.Find("screen_name").Value;
					string profileImg = (string) user.Find("profile_image_url").Value;

			        userStore.Add(twitterId, screenname, profileImg);
					friends.Add(twitterId);
				}
			}

    		DataDocValue nextCustor = users.Find("/next_cursor");
			if ((nextCustor != null) && ((long)nextCustor.Value > 0))
			{
				innerSession.ApiCaller.RequestRawAsync(t => t.Users().GetFriends().GetCursor((long)nextCustor.Value).AsJson(), GetFriendsNames_Complete, innerSession, true);
			}
		}
    }

}
